package com.wsoft.bpm.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wsoft.core.exception.Asserts;
import com.wsoft.core.service.CommonMemberService;
import com.wsoft.core.vo.MemberVO;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 定时任务记录系统超过审批时长阈值的数据
 *
 * @author zhonglj
 * @date 2024/12/23 10:39
 **/
@Slf4j
@Service
public class OverApprovalThresholdJob implements Job {
    public static final String INTERVAL_SECOND_LIMIT = "intervalSecondLimit";
    @Resource
    private TaskService taskService;
    @Resource
    private CommonMemberService memberService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        JobDataMap dataMap = jobExecutionContext.getMergedJobDataMap();
        // 获取间隔时间单位秒
        Integer interval = dataMap.getIntegerFromString(INTERVAL_SECOND_LIMIT);
        if (interval == null || interval.intValue() == 0) {
            return;
        }

        DateTime now = DateUtil.date();
        // 获取审批中的超过阈值的记录
        List<Task> overTimeTodoList = taskService.createTaskQuery()
                .active()
                .list().stream()
                .filter(task -> DateUtil.offsetSecond(task.getCreateTime(), interval).isBefore(now))
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(overTimeTodoList)) {
            // 存在超时的代办任务
            StringBuilder builder = new StringBuilder();
            String template = "任务:【{}】,审批人:【{}】,超出审批时长阈值:{}!";
            Map<Long, MemberVO> memberVOMap = memberService.getMemberList().stream()
                    .collect(Collectors.toMap(MemberVO::getId, e -> e));

            for (Task task : overTimeTodoList) {
                String assigneeName = Optional.ofNullable(memberVOMap.get(task.getAssignee())).get().getName();
                String between = DateUtil.formatBetween(task.getCreateTime(), now);
                String taskName = task.getName();
                builder.append(StrUtil.format(template, taskName, assigneeName, between)).append("\n");
            }

            Asserts.fail(builder.toString());
        }

    }

}
